package com.yusheng.tr.auth.service;

import com.yusheng.constant.CacheConstants;
import com.yusheng.constant.Constants;
import com.yusheng.constant.SecurityConstants;
import com.yusheng.constant.UserConstants;
import com.yusheng.domain.R;
import com.yusheng.enums.UserStatus;
import com.yusheng.exceptions.BizException;
import com.yusheng.exceptions.ExceptionEnum;
import com.yusheng.exceptions.ServiceException;
import com.yusheng.service.RedisService;
import com.yusheng.tr.common.core.context.AuthenticationContextHolder;
import com.yusheng.tr.common.core.entity.system.SysUser;
import com.yusheng.tr.common.core.manager.AsyncManager;
import com.yusheng.tr.common.core.manager.factory.AsyncFactory;
import com.yusheng.tr.common.core.model.vo.LoginUser;
import com.yusheng.tr.common.core.openfeign.RemoteUserService;
import com.yusheng.tr.common.core.service.TokenService;
import com.yusheng.tr.common.core.utils.SecurityUtils;
import com.yusheng.utils.MessageUtils;
import com.yusheng.utils.string.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author yusheng
 */
@Component
public class SysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;
    @Resource
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysRecordLogService recordLogService;

    /**
     * 登录
     */
    public String login(String username, String password) {
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new BizException(ExceptionEnum.BAD_METHOD);
            }else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMessage());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }
}
